package cn.tedu.egweibo3.controller;

import cn.tedu.egweibo3.common.response.JsonResult;
import cn.tedu.egweibo3.common.response.StatusCode;

import cn.tedu.egweibo3.mapper.UserMapper;
import cn.tedu.egweibo3.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo3.pojo.dto.UserRegDTO;
import cn.tedu.egweibo3.pojo.entity.User;
import cn.tedu.egweibo3.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Api(tags = "01.用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
     @Autowired
    private UserMapper userMapper;
     @ApiOperation(value = "用户注册")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO = "+userRegDTO);
        //用户名是否存在
        UserVO userVO = userMapper.selectReg(userRegDTO.getUsername());
        if (userVO!=null){//存在
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);//用户名已存在
        }
        //如果不存在
        User user = new User();
            BeanUtils.copyProperties(userRegDTO,user);
            user.setCreated(new Date());
            userMapper.insertReg(user);
            return new JsonResult(StatusCode.OPERATION_SUCCESS);//注册成功
        }
        @ApiOperation(value = "用户登录")
        @PostMapping("login")
        public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
         log.debug("userLoginDTO =" +userLoginDTO);
         //获取用户输入的用户名是否正确
         UserVO userVO = userMapper.selectReg(userLoginDTO.getUsername());
         if (userVO==null){//如果为空则说明错误
             return new JsonResult(StatusCode.USERNAME_ERROR);//返回用户名错误
         }
         //看密码正不正确
         if (userLoginDTO.getPassword().equals(userVO.getPassword())){
             //会话保持技术，在登录前添加
             session.setAttribute("user",userVO);
             //如果正确则登陆成功
             return new JsonResult(StatusCode.LOGIN_SUCCESS);
         }
         //如果错误，则返回密码错误
         return new JsonResult(StatusCode.PASSWORD_ERROR);
        }

        //获取当前用户
        @ApiOperation("获取当前用户")
     @GetMapping("entUser")
    public JsonResult entUser(@ApiIgnore HttpSession session){
         UserVO userVO = (UserVO) session.getAttribute("user");
         return new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);
        }

      @ApiOperation("退出当前用户")
    @GetMapping("logout")
    public  void logout(@ApiIgnore HttpSession session){

        session.removeAttribute("user");
      }
}

